//
//  XS_LoginVC.swift
//  XueDao
//
//  Created by 韩云智 on 2020/12/3.
//

//https://xdapi.yaoxuedao.com.cn/apple-app-site-association
import UIKit
import AuthenticationServices
import Toast_Swift

class XS_WeixinM : XS_BaseModel {
    var scope = ""
    var expires_in = 0
    var openid = ""
    var unionid = ""
    var access_token = ""
    var refresh_token = ""
}

class XS_LoginVC: XS_BaseVC {
    
    private lazy var isAgree = true
    private lazy var btnView = getButtonView()
    
    override func upConfig() {
        isStatusBarBlack = false
        shouldNavBarHidden = true
        shouldEndEditing = true
    }
    override func upView() {
        let imgV = UIImageView(image: UIImage(named: "位图 + 矩形 蒙版"))
        view.addSubview(imgV)
        imgV.snp.makeConstraints { m in
            m.edges.equalToSuperview()
        }
        
        let btn = XS_NoHighlightBtn()
        btn.setTitle("游客模式", for: .normal)
        btn.setTitleColor(#colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), for: .normal)
        btn.titleLabel?.font = .xsFont(name: .medium, .scale*16)
        view.addSubview(btn)
        btn.snp.makeConstraints { m in
            m.top.equalTo(.barHeight + .scale*14)
            m.right.equalTo(-.scale*16)
        }
        btn.rx.tap.asDriver()
            .drive(onNext: { [weak self] in
                self?.navigationController?.popViewController(animated: true)
            }).disposed(by: disposeBag)
        
        do {
            let tLab = UILabel.xsLabel(size: .scale*26, fontName: .semibold, color: #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), text: "手机号登录/注册")
            view.addSubview(tLab)
            tLab.snp.makeConstraints { m in
                m.left.equalTo(.scale*40)
                m.top.equalTo(.barHeight + .scale*76)
            }
            
            let dLab = UILabel.xsLabel(size: .scale*16, fontName: .regular, color: #colorLiteral(red: 1, green: 1, blue: 1, alpha: 0.6), text: "未注册用户验证通过后将自动注册")
            view.addSubview(dLab)
            dLab.snp.makeConstraints { maker in
                maker.left.equalTo(.scale*40)
                maker.top.equalTo(tLab.snp.bottom).offset(.scale*10)
            }
            
            let bgView = UIView()
            bgView.layer.cornerRadius = .scale*28
            bgView.layer.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 0.3)
            view.addSubview(bgView)
            bgView.snp.makeConstraints { m in
                m.width.equalTo(.scale*295)
                m.height.equalTo(.scale*48)
                m.centerX.equalToSuperview()
                m.top.equalTo(.barHeight + .scale*188)
            }
            
            let btn = XS_NoHighlightBtn()
            btn.layer.cornerRadius = .scale*28
            btn.layer.backgroundColor = #colorLiteral(red: 0.1647058824, green: 0.7411764706, blue: 0.6117647059, alpha: 0.6)
            btn.setTitle("获取验证码", for: .normal)
            btn.setTitleColor(#colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), for: .normal)
            btn.titleLabel?.font = .xsFont(name: .regular, .scale*18)
            view.addSubview(btn)
            btn.snp.makeConstraints { m in
                m.width.equalTo(.scale*295)
                m.height.equalTo(.scale*48)
                m.centerX.equalToSuperview()
                m.top.equalTo(bgView.snp.bottom).offset(.scale*24)
            }
            
            let lab = UILabel.xsLabel(size: .scale*18, fontName: .semibold, color: #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), text: "+86")
            bgView.addSubview(lab)
            lab.snp.makeConstraints { m in
                m.centerX.equalTo(.scale*41)
                m.centerY.equalToSuperview()
            }
            
            let text = NSMutableAttributedString(string: "输入手机号码")
            text.yy_font = .xsFont(name: .regular, .scale*18)
            text.yy_color = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 0.6)
            let textField = UITextField()
            textField.attributedPlaceholder = text
            textField.textColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
            textField.font = .xsFont(name: .regular, .scale*18)
            textField.keyboardType = .numberPad
            textField.delegate = self
            bgView.addSubview(textField)
            textField.snp.makeConstraints { m in
                m.edges.equalTo(UIEdgeInsets(top: 0, left: .scale*90, bottom: 0, right: .scale*10))
            }
            
            btn.rx.tap.asDriver()
                .drive(onNext: { [weak self] in
                    textField.resignFirstResponder()
                    guard let text = textField.text, text.xsCheck(.phone) else {
                        self?.view.xsShowMsg("请正确输入手机号")
                        return
                    }
                    guard let isAgree = self?.isAgree, isAgree == true else {
                        self?.view.xsShowMsg("请先勾选使用条款和隐私政策")
                        return
                    }
                    let vc = XS_VerificationCodeVC()
                    vc.phone = text
                    self?.navigationController?.pushViewController(vc, animated: true)
                }).disposed(by: disposeBag)
        }
        do {
            let btn = XS_NoHighlightBtn()
            btn.isSelected = self.isAgree
            btn.setBackgroundImage(UIImage(named: "矩形_1"), for: .normal)
            btn.setBackgroundImage(UIImage(named: "编组 7"), for: .selected)
            view.addSubview(btn)
            btn.snp.makeConstraints { m in
                m.width.height.equalTo(.scale*15)
                m.left.equalTo(.scale*60)
                m.bottom.equalTo(-.scale*26 - .bottomHeight)
            }
            btn.rx.tap.asDriver()
                .map { !btn.isSelected }
                .drive(onNext: { [weak self] set in
                    self?.isAgree = set
                    btn.isSelected = set
                }).disposed(by: disposeBag)
            
            let label = YYLabel()
            view.addSubview(label)
            label.snp.makeConstraints { m in
                m.centerY.equalTo(btn.snp.centerY)
                m.left.equalTo(btn.snp.right).offset(.scale*9)
            }
            
            let text = NSMutableAttributedString(string: "我已阅读并同意")
            let text1 = NSMutableAttributedString(string: " 使用条款和隐私政策")
            text1.yy_underlineStyle = .single
            text1.yy_underlineColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
            text1.yy_setTextHighlight(text1.yy_rangeOfAll(), color: #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), backgroundColor: nil) { _, attr, _, _ in
                self.openPrivacyPolicy()
            }
            text.append(text1)
            text.yy_font = .xsFont(name: .regular, .scale*14)
            text.yy_color = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
            label.attributedText = text
            
            if let btnView = btnView {
                view.addSubview(btnView)
                btnView.snp.makeConstraints { maker in
                    maker.height.equalTo(.scale*56)
                    maker.bottom.equalTo(btn.snp.top).offset(-.scale*20)
                    maker.left.right.equalToSuperview()
                }
            }
        }
    }
    
    @objc func openPrivacyPolicy() {
        let privacyPolicyUrl = "http://xdapp.yaoxuedao.com.cn/privacyPolicy"
        let webVC = XS_WebPageVC()
        webVC.loadUrl(privacyPolicyUrl)
        XS_NVC.shared.pushViewController(webVC, animated: true)
    }
    
    private func getButtonView() -> UIView? {
        let btns = [getAppleButton(), getWeixinButton()].compactMap { $0 }
        guard btns.count > 0 else { return nil }
        let view = UIView()
        let label = UILabel.xsLabel(size: .scale*16, fontName: .medium, color: #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1), alignment: .center, text: "第三方登录")
        view.addSubview(label)
        label.snp.makeConstraints { maker in
            maker.centerX.equalToSuperview()
            maker.bottom.equalTo(view.snp.top).offset(-.scale*20)
        }
        let left = .scale*CGFloat(375 - 106*btns.count + 50)/2
        for (index, btn) in btns.enumerated() {
            btn.frame = CGRect(x: .scale*CGFloat(index)*104 + left, y: 0, width: .scale*50, height: .scale*50)
            view.addSubview(btn)
        }
        return view
    }
    
    private func getWeixinButton() -> UIView? {
        guard WXApi.isWXAppInstalled() else { return nil }
        NotificationCenter.default.rx
            .notification(Notification.Name("XS_WeixinM"))
            .subscribe(onNext: { [weak self] noti in
                guard let `self` = self, let object = noti.object as? XS_WeixinM else { return }
                print(object.openid)
                XS_NetWork.requestJson("/user/openidLogin", parameters: ["openId":object.openid])
                    .mapModel(type: XS_UserInfoM.self)
                    .subscribe(onNext: { [weak self] model, resp in
                        guard resp.success, let model = model else {
                            let vc = XS_LoginThreeVC()
                            vc.openid = object.openid
                            self?.navigationController?.pushViewController(vc, animated: false)
                            return
                        }
                        XS_Singleton.shared.infoModel = model
                        if (model.isAnswer != 0) {
                            self?.navigationController?.popToRootViewController(animated: true)
                        } else {
                            let vc = XS_Q1VC()
                            vc.title = "问题1，共3个"
                            vc.text = "您的就业方向是什么？"
                            vc.desc = "请回答下列问题，方便我们为您量身定制课程计划。"
                            self?.navigationController?.pushViewController(vc, animated: true)
                        }
                    }).disposed(by: self.disposeBag)
            }).disposed(by: disposeBag)
        let button = XS_NoHighlightBtn()
        button.backgroundColor = .black
        button.layer.cornerRadius = .scale*25
        button.setImage(UIImage(named: "编组_2"), for: .normal)
        button.rx.tap.asDriver()
            .drive(onNext: { [weak self] _ in
                guard let `self` = self else { return }
                let req = SendAuthReq()
                req.scope = "snsapi_userinfo"
                req.state = "App"
                WXApi.sendAuthReq(req, viewController: self, delegate: nil)
            }).disposed(by: disposeBag)
        return button
    }
    private func getAppleButton() -> UIView? {
        guard #available(iOS 13.0, *) else { return nil }
        let view = UIView()
        let button = ASAuthorizationAppleIDButton(authorizationButtonType: .signIn, authorizationButtonStyle: .black)
        button.bounds = CGRect(x: 0, y: 0, width: .scale*50, height: .scale*50)
        button.cornerRadius = .scale*25
        button.addTarget(self, action: #selector(userAppIDLogin), for: .touchUpInside)
        view.addSubview(button)
        button.snp.makeConstraints { m in
            m.width.height.equalTo(.scale*50)
            m.center.equalToSuperview()
        }
        return view
    }
}

extension XS_LoginVC: ASAuthorizationControllerDelegate {
    @objc func userAppIDLogin() {
        guard #available(iOS 13.0, *) else { return }
        self.view.makeToastActivity(CGPoint.init(x: .screenWidth / 2, y: .screenHeight / 2))
        let appleIdProvider = ASAuthorizationAppleIDProvider()
        let request = appleIdProvider.createRequest()
        let controller = ASAuthorizationController(authorizationRequests: [request])
        controller.delegate = self
//        controller.presentationContextProvider = self
        controller.performRequests()
    }
    
    @available(iOS 13.0, *)
    func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
        switch authorization.credential {
        case let credential as ASAuthorizationAppleIDCredential:
            print(credential.user)
            XS_NetWork.requestJson("/user/iosidLogin", parameters: ["iosid":credential.user])
                .mapModel(type: XS_UserInfoM.self)
                .subscribe(onNext: { [weak self] model, resp in
                    self?.view.hideToastActivity()
                    guard resp.success, let model = model else {
                        let vc = XS_LoginThreeVC()
                        vc.iosid = credential.user
                        self?.navigationController?.pushViewController(vc, animated: false)
                        return
                    }
                    XS_Singleton.shared.infoModel = model
                    if (model.isAnswer != 0) {
                        self?.navigationController?.popToRootViewController(animated: true)
                    } else {
                        let vc = XS_Q1VC()
                        vc.title = "问题1，共3个"
                        vc.text = "您的就业方向是什么？"
                        vc.desc = "请回答下列问题，方便我们为您量身定制课程计划。"
                        self?.navigationController?.pushViewController(vc, animated: true)
                    }
                }).disposed(by: self.disposeBag)
        default:
            break
        }
    }
    
    @available(iOS 13.0, *)
    func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
        // 授权回调失败
        self.view.hideToastActivity()
        var errorMsg = ""
        switch error {
        case ASAuthorizationError.unknown:
            errorMsg = "授权请求失败未知原因"
            break
        case ASAuthorizationError.canceled:
            errorMsg = "用户取消了授权请求"
            break
        case ASAuthorizationError.invalidResponse:
            errorMsg = "授权请求响应无效"
            break
        case ASAuthorizationError.notHandled:
            errorMsg = "未能处理授权请求"
            break
        case ASAuthorizationError.failed:
            errorMsg = "授权请求失败"
            break
            
        default:
            errorMsg = "授权失败"
            break
        }
        self.view.xsShowMsg(errorMsg)
    }
}

extension XS_LoginVC: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        if textField.text!.count >= 11 && !string.isEmpty  {
            return false
        }
        return true
    }
}
